// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 获取TabBar图标配置
exports.main = async (event, context) => {
  try {
    console.log('getTabBarIcons云函数被调用')
    
    // 查询所有活跃的TabBar图标配置
    const result = await db.collection('tabbar_icons')
      .where({
        isActive: true
      })
      .orderBy('iconType', 'asc')
      .get()
    
    console.log('查询结果:', result)
    
    if (result.data && result.data.length > 0) {
      // 构建图标映射对象
      const icons = {}
      
      result.data.forEach(item => {
        icons[item.iconType] = {
          normal: item.imageUrl,
          selected: item.selectedImageUrl || item.imageUrl
        }
      })
      
      console.log('构建的图标映射:', icons)
      
      return {
        success: true,
        data: icons,
        message: '获取TabBar图标配置成功'
      }
    } else {
      console.log('未找到活跃的TabBar图标配置，返回空对象')
      return {
        success: true,
        data: {},
        message: '暂无自定义TabBar图标配置'
      }
    }
    
  } catch (error) {
    console.error('getTabBarIcons云函数执行失败:', error)
    return {
      success: false,
      error: error.toString(),
      message: '获取TabBar图标配置失败'
    }
  }
}